package com.abc.rule.aviator;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class DayBetweenFunction extends AbstractFunction {
   @Override
   public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {

      try {
         Object left = FunctionUtils.getJavaObject(arg1, env);

         Date cur = new Date();

         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

         long dayBetween = getDayNum(format.parse(left.toString()), cur) ;

         System.out.println(dayBetween);

         return new AviatorLong(dayBetween);
      }
      catch (Exception e) {
         System.out.println(e.getMessage());
         return new AviatorLong(0);
      }
   }

   @Override
   public String getName() {
      return "dayBetween";
   }

   public static long getDayNum(Date beginDate, Date endDate) {
      return (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
   }
}